<?php
	
	function array_value($arr, $key, $default = '') {
		return isset($arr[$key]) ? $arr[$key] : $default;
	}

	//遍历 目录
	function show_dir($path){
		if (!$path = handle_dir($path)) {
			$GLOBALS['error_msg'][] = '没有这个目录，无法进行打开！';
			return false;
		}
		if (!$dir = @opendir($path)) {
			$GLOBALS['error_msg'][] = '不是一个合法的目录或者因为权限限制或文件系统错误而不能打开目录';
			return false;
		}
		$tmp_arr = [];
		$tmp_arr['dirnum'] = 0;
		$tmp_arr['filenum'] = 0; 
		while ($file = readdir($dir)) {
			if ($file === '.' || $file=== '..') {
				continue;
			}
			$file_info = [];
			if (is_file($path.'/'.$file)) {
				$file_info['filename'] = str_convert($file);
				$file_info['dir']  = $path;
				$file_info['filePath'] = $path.'/'.$file;
				$file_info['fileSize'] = getsize(filesize($file_info['filePath']));
				$file_info['filemtime']= date('Y-m-d H:i',filemtime($file_info['filePath']));
				$file_info['filectime']= date('Y-m-d H:i',filectime($file_info['filePath']));
				$file_info['suffix'] = substr(strrchr($file_info['filePath'], '.'), 1);
				$file_info['zip'] = $file_info['suffix']==='zip'?'zip':false;
				$file_info['viewedit'] = in_array($file_info['suffix'], $GLOBALS['conf']['file_view_edit']);
				$file_info['download'] = create_url('file','download',['path'=>$file_info['filePath']]);
				$file_info['chmod'] = getchmod($file_info['filePath']);
				$tmp_arr['file'][] = $file_info;
				$tmp_arr['filenum']++;
			}else{
				$file_info['dirname'] = str_convert($file);
				$file_info['dir'] = $path;
				$file_info['filePath'] = $path.'/'.$file;
				$file_info['chmod'] = getchmod($file_info['filePath']);
				$file_info['openurl'] = create_url('index','',['path'=>$file_info['filePath']]);
				$tmp_arr['dir'][] = $file_info;
				$tmp_arr['dirnum']++;
			}
		}
		closedir($dir);
		return $tmp_arr;
	}

	//计算文件大小
	function getsize($size){
	    if ($size < 1024) {
	        return $size . " B";
	    } elseif ($size < 1024 * 1024) {
	        return number_format($size / 1024, 3) . " KB";
	    } elseif ($size < 1024 * 1024 * 1024) {
	        return number_format($size / 1024 / 1024, 3) . " MB";
	    } elseif ($size < 1024 * 1024 * 1024 * 1024) {
	        return number_format($size / 1024 / 1024 / 1024, 3) . " GB";
	    } else {
	        return number_format($size / 1024 / 1024 / 1024 / 1024, 3) . " TB";
	    }
	}
	//获取文件权限
	function getchmod($filepath){
    	return substr(base_convert(@fileperms($filepath),10,8),-4);
	}

	//处理目录

	function handle_dir($path){
		//转为规范化绝对路径
		if ($path = realpath($path)) {
			return $path;
		}
		return false;
	}

	//编码url
	function encode($url){
		return rawurlencode($url);
	}
	//解码
	function decode($url){
		return rawurldecode($url);
	}


	//文件下载
	function download($path)
	{
	    $size = filesize($path);
	    (isset($_SERVER['HTTP_RANGE']) && !empty($_SERVER['HTTP_RANGE']) && $range = substr($_SERVER['HTTP_RANGE'], 6)) || $range = '0-' . ($size - 1);
	    if (substr($range, -1) == '-') {
	        $init = substr($range, 0, -1);
	        $stop = $size - 1;
	    } elseif (substr($range, 0, 1) == '-') {
	        $init = $size - substr($range, 1) - 1;
	        $stop = $size - 1;
	    } else {
	        $init_stop = explode('-', $range);
	        $init = $init_stop[0];
	        $stop = $init_stop[1];
	    }
	    if (isset($_SERVER['HTTP_RANGE'])) {
	        header('HTTP/1.1 206 Partial Content');
	    }
	    header('Accept-Ranges: bytes');
	    header('Content-Type: application/force-download');
	    header('Content-Disposition: attachment; filename=' . get_path_name($path));
	    header("Content-Range: bytes $init-$stop/$size");
	    header('Content-Length: ' . ($stop - $init + 1));
	    $fp = fopen($path, "rb");
	    fseek($fp, $init);
	    while (!feof($fp)) {
	        echo fread($fp, 4096);
	        if (ftell($fp) > $stop) {
	            break;
	        }
	    }
	    fclose($fp);
	    die;
	}

	//路径去文件名
	function get_path_name($path)
	{
	    $path = str_replace("\\", "/", $path);
	    $path = explode("/", $path);
	    return str_convert($path[count($path) - 1]);
	}
	//检测 path
	function is_path($jump = false){
		$path = param('path');
		if (empty($path) OR !file_exists($path)) {
			jump('提供的路径错误,请输入正确的路径！',$GLOBALS['REFERER']);
		}
	}
	// GET now path
	function get_now_path(){
		$path = empty(param('path'))?$GLOBALS['conf']['root_path']:decode(param('path'));
		return dirname($path);
	}
	// GET now file
	function get_now_file(){
		return empty(param('path')) || !is_file(param('path'))?'':decode(param('path'));
	}
	//转码
	function str_convert($str,$encode = 'UTF-8',$enlist = 'auto,CP936')
	{
	    if (!function_exists("mb_convert_encoding")) return $str;
	    return mb_convert_encoding($str, $encode, $enlist);
	}
	//上传文件
	function upload($key = 'file',$toPath = './'){
		$error = [
				1 => '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。',
				2 => '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。',
				3 => '文件只有部分被上传。',
				4 => '没有文件被上传。',
				6 => '找不到临时文件夹。',
				7 => '文件写入失败。'
		];
		if(empty($_FILES) || empty($_FILES[$key])) return ['error'=>false,'message'=>'没有文件上传！'];
		$file = $_FILES[$key];
		if($file['error'] !== 0 ) return ['error'=>false,'message'=>$error[$file['error']]];
		$config = $GLOBALS['conf']['UPLOADS'];
		// 检测 文件大小限制
		if ($config['size'] !== 0) {
			if($file['size'] > $config['size']*1024) return ['error'=>false,'message'=>'上传文件超出限制大小!'];
		}
		//取后缀名
		$suffix = substr(strrchr($file['name'], '.'),1);
		// 检测 后缀限制
		if (!empty($config['suffix']) AND is_array($config['suffix'])) {
			if(!in_array($suffix, $config['suffix'])) return ['error'=>false,'message'=>'文件类型不允许!'];
		}
		$newName = $file['name'];
		// 是否 随机命名
		if ($config['byName']) {
			$newName = date('YmdHis').uniqid().'.'.$suffix;
		}
		//检查 上传文件路径
		if (!file_exists($toPath)) {
			@mkdir($toPath,0777,true);
		}
		$newName  = $toPath.'/'.$newName;
		if (move_uploaded_file($file['tmp_name'], $newName)) {
			return ['error'=>true,'message'=>'上传成功!'];
		}
		return ['error'=>false,'message'=>'上传失败!'];
	}

	// 解压文件
	function unzip($zipfile,$toPath){
		if(!$zip = zip_open($zipfile)) return ['error'=>false,'message'=>'打开失败！'];
		$error_file = [];
		// var_dump($toPath);die;
		while ($option = zip_read($zip)) {
			$file = zip_entry_name($option);
			if (is_dir($file)) {
				@mkdir($toPath.'/'.$file,0777,true);
			}else{
				$content = zip_entry_read($option,zip_entry_filesize($option));
				if(file_put_contents($toPath.'/'.$file,$content) === false){
					$error_file[] = $file.'&nbsp;';
				}
				// var_dump($toPath.'/'.$file);
			}
			zip_entry_close($option);
		}
		zip_close($zip);
		if (empty($error_file)) {
			return ['error'=>true,'message'=>'zip解压成功！'];
		}
		return ['error'=>false,'message'=>'zip解压[ '.implode(',', $error_file).' ]失败！'];
	}
	// 删除文件夹 $type false 文件夹不为空不允许删除 true 递归删除
	function delDir($path,$type=false){

	}





